(function () {
    "use strict";

    var defineType = require("./define-type");
    var EventBus = require("./event-bus");

    var storageKeyRx = /^document-editor\//;

    var DocumentSync = defineType(function (document, storage) {
        this.document = document;
        this.storage = storage || localStorage;
        this.version = document.version;
        this.inactive = false;
        this.init();
    }, new EventBus, {
        storagePath: function () {
            return "document-editor/" + this.document.id;
        },

        load: function () {
            var data = this.storage.getItem(this.storagePath());
            if (!data) {
                return;
            }

            var json = JSON.parse(data);
            if (!json || json.version <= this.version) {
                return;
            }

            this.inactive = true;
            this.document.fromJson(json);
            this.version = this.document.version;
            this.inactive = false;
        },

        save: function () {
            if (this.inactive) {
                return;
            }

            if (this.document.version <= this.version) {
                return;
            }

            var storagePath = this.storagePath();
            var data = this.storage.getItem(storagePath);
            var json;
            if (data) {
                json = JSON.parse(data);
                if (json.version >= this.document.version) {
                    return;
                }
            }

            json = this.document.toJson();
            data = JSON.stringify(json);
            this.storage.setItem(this.storagePath(), data);
            this.version = this.document.version;
        },

        init: function () {
            this.document.on("change", this.save.bind(this));
            window.addEventListener("storage", this.load.bind(this));
        }
    });

    DocumentSync.list = function (storage) {
        storage = storage || localStorage;
        var length = storage.length;
        var list = [];
        for (var i = 0; i < length; i++) {
            var key = storage.key(i);
            if (!key) {
                continue;
            }

            var m = key.match(storageKeyRx);
            if (!m) {
                continue;
            }

            var id = parseInt(key.substr(m[0].length), 10);
            if (isNaN(id)) {
                continue;
            }

            list.push(id);
        }

        return list;
    };

    module.exports = DocumentSync;
})();
